﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using VNPT.Excel;
using System.Threading;
using DevExpress.XtraGrid;
using VNPT.Utility;
using VNPT.Data;

namespace VNPT.DoiSoat.DoiSoat
{
    public partial class u109_1800_1900DLK_VTN : VNPT.Core.uBase
    {
        public u109_1800_1900DLK_VTN()
        {
            InitializeComponent();

            StyleFormatCondition condition1 = new DevExpress.XtraGrid.StyleFormatCondition();
            condition1.Appearance.BackColor = Color.Red;
            condition1.Appearance.Options.UseBackColor = true;
            condition1.Condition = FormatConditionEnum.Between;
            condition1.Value1 = "1";
            condition1.Value2 = "101";
            condition1.Column = colTiLe_Phut;
            myGridView1.FormatConditions.Add(condition1);

        }

        private List<string> GetSheetName(string Path)
        {
            List<string> kq= new List<string>();
            if (System.IO.File.Exists(Path))
            {
                FileStream stream = File.Open(Path, FileMode.Open);//, FileMode.Open, FileAccess.Read);
                IExcelDataReader excelReader;
                if (Path.EndsWith(".xls"))
                {
                    excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else
                {
                    if (Path.EndsWith(".xlsx"))
                    {
                        excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("File không hợp lệ!");
                        return null;
                    }
                }

                excelReader.IsFirstRowAsColumnNames = true;
                DataSet result = excelReader.AsDataSet();

                foreach (var item in result.Tables)
                {
                    kq.Add(((DataTable)item).TableName);
                }
                return kq;
            }
            return null;
        }

        List<DoiSoat18001900> li = new List<DoiSoat18001900>();
       
        List<DoiSoat18001900> GetList(string PathExcel, string SheetName)
        {
            li.Clear();
            FileStream stream = File.Open(PathExcel, FileMode.Open);//, FileMode.Open, FileAccess.Read);
            IExcelDataReader excelReader;
            if (PathExcel.EndsWith(".xls"))
            {
                excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            }
            else
            {
                if (PathExcel.EndsWith(".xlsx"))
                {
                    excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("File không hợp lệ!");
                    return null;
                }
            }


            excelReader.IsFirstRowAsColumnNames = true;
            DataSet result = excelReader.AsDataSet();
            foreach (var item in result.Tables[SheetName].Rows)
            {
                var dt = ((DataRow)item);

                int phut = 0;
                int.TryParse((dt[1] ?? "0").ToString(), out phut);

                int dongia = 0;
                int.TryParse((dt[2] ?? "0").ToString(), out dongia);

                int thanhtien = 0;
                int.TryParse((dt[3] ?? "0").ToString(), out thanhtien);

                string DausoDep = System.Text.RegularExpressions.Regex.Replace(dt[0].ToString(), @"x+", "%");

                if (!DausoDep.EndsWith("%"))
                {
                    DausoDep += "%";
                }

               //string table = string.Format("Select SUM(CEIL(tg_goi/60)) phut from DAKLAK.ctdt_{0}{1:D2}01@daklak_3  where substr(bigoi,1,{2}) = '{3}'",
                //    DoiSoatSetting.NAM, DoiSoatSetting.THANG, DausoDep.Length, DausoDep);

                string query = string.Format(DoiSoatSetting.SQL_DV_1800_1900_VTT_VTN, DoiSoatSetting.NAM, DoiSoatSetting.THANG, DausoDep);

                //string table = string.Format("Select SUM(CEIL(tg_goi/60)) phut from DAKLAK.ctdt_{0}{1:D2}01@daklak_3  where bigoi LIKE '{2}'",
                //                    DoiSoatSetting.NAM, DoiSoatSetting.THANG, DausoDep);
                var it = new DoiSoat18001900()
                {
                    Cuoc = 0,
                    Cuoc_DLK = 0,
                    DauSo = dt[0].ToString(),
                    DonGia = dongia,
                    GhiChu = "",
                    Phut = phut,
                    Phut_DLK = 0,
                    Query = query,
                    TrangThai = ""
                };
                li.Add(it);
            }

            foreach (var item in li.Where(p => p.CoX).ToList())
            {
                item.Query += GetDuoiSQL(li);
            }
            return li;
        }

        string GetDuoiSQL(List<DoiSoat18001900> li)
        {
            string kq = "";
            foreach (var item in li.Where(p => !p.CoX))
            {
                kq += "', '" + item.DauSo;
            }
            return " Where substr(bigoi,1,8) NOT IN (" + kq.Right(kq.Length - 2) + "')";
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (lookUpEdit1.EditValue != null)
            {
                var SheetName = lookUpEdit1.EditValue.ToString();
                myGridControl1.DataSource = GetList(btnGoiDi.Text, SheetName);
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Chưa chọn sheet!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            new VNPT.Utility.Grid.GridExport().Export(myGridControl1);

        }

        private bool _is_stoped;
        private int num_threads;
     
        private void DoWorkMultiThread(object o)
        {
            if (DbServer.Conn.State == ConnectionState.Closed)
            {
                DbServer.Open();
            }
            if (_is_stoped)
            {
                return;
            }

            int val = 0;
            int index = (int)o;
            Thread.Sleep(100 + index * 10);
            li[index].TrangThai = "Wait...";

            try
            {
                var cmd = new CommandConfig(li[index].Query);

                int.TryParse(DbServer.ExecuteScalar(cmd).ToString(), out val);
                li[index].Phut_DLK = val;
                li[index].TrangThai = "Ok";
            }
            catch (Exception)
            {
                li[index].TrangThai = "Lỗi";
            }
            
            UpdateGridControl(index);
            if (index == li.Count-1)
            {
                myGridView1.HideLoadingPanel();
                DevExpress.XtraEditors.XtraMessageBox.Show("Đã tính toán xong, vui lòng xin kiểm tra lại!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                var di = (float)li.Sum(p => p.Phut);
                var di_Dlk = (float)li.Sum(p => p.Phut_DLK);
                float tlDi = (di > di_Dlk ? (di - di_Dlk) / di : (di_Dlk - di) / di_Dlk) * 100;
                lblTiLeChung.Text = string.Format("Tỉ lệ: {0:n2}%",tlDi);

            }
        }

        private void UpdateGridControl(int index)
        {
            this.myGridControl1.BeginInvoke
            (
                new MethodInvoker
                (
                    delegate
                    {
                        this.myGridView1.MakeRowVisible(index,true);
                        myGridControl1.RefreshDataSource();
                        myGridControl1.Refresh();
                    }
                )
            );
        }
     
        private void btnTinhToan_Click(object sender, EventArgs e)
        {
            myGridView1.ShowLoadingPanel();
            var ctHost = string.Format("ct_host_810_{0}_{1:D2}a_dlk", DoiSoatSetting.NAM, DoiSoatSetting.THANG);
            var ctGPhone = string.Format("ct_gphone_{0}_{1:D2}_dlk", DoiSoatSetting.NAM, DoiSoatSetting.THANG);
            if (!DbServer.TableExists(ctHost) || !DbServer.TableExists(ctGPhone))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Chưa có dữ liệu của tháng, vui lòng kiểm tra lại!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            myGridControl1.ForceInitialize();
            if (DbServer.Conn.State == ConnectionState.Closed)
            {
                DbServer.Open();
            }

            _is_stoped = false;
            num_threads = (int)mySpinEdit1.Value;
            int minWorker, minIOC;

            ThreadPool.GetMinThreads(out minWorker, out minIOC);
            ThreadPool.SetMaxThreads(num_threads, num_threads + 10);

            int dem = 0;
            foreach (var s in li)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(DoWorkMultiThread), (object)dem);
                dem++;
            }
        }

        private void btnGoiDi_EditValueChanged(object sender, EventArgs e)
        {
            lookUpEdit1.Properties.DataSource = GetSheetName(btnGoiDi.Text);
        }

        private void btnSQL_Click(object sender, EventArgs e)
        {
            new fEditSQL("SQL_DV_1800_1900_VTT_VTN",
               "Lấy phút và cuộc gọi các VTT/TP đến các dịch vụ 108x, 801x, 802x, 1089 của DakLak",
                "Trả về MA_MANG, PHUT, CUOC. Các tham số {0}= Năm, {1:D2}= Tháng").ShowDialog();
        }
    }
}
